import pygame
import sys
from ticai import AiBrain

# colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

WIN_SIZE = (400, 400)
BOX_SIZE = 100

START_X = 50
START_Y = 50


board = [[0] * 3 for _ in range(3)]
# debug
# board[0][1] = 2
# board[1][1] = 2
# board[2][1] = 2

man = 1
ai = 2

current_turn = man
winner = None

AI = AiBrain()

# --------------- game world  ---------------

pygame.init()
screen = pygame.display.set_mode(WIN_SIZE)
pygame.display.set_caption("AI TicTacToe by tpig")

img_x = pygame.image.load("img/x.png")
img_o = pygame.image.load("img/o.png")

fnt = pygame.font.SysFont("微软雅黑", 60, "bold")
x_win = fnt.render("X Win!", True, RED, WHITE)
o_win = fnt.render("O Win!", True, RED, WHITE)
tie = fnt.render("TIE :-(", True, RED, WHITE)


def print_board():
    """打印棋盘，调试用"""
    for row in board:
        print(row)

def pos_to_board(pos):
    x, y = pos
    if (x < 0) or (y < 0) or \
            x > START_X + 3 * BOX_SIZE or \
            y > START_Y + 3 * BOX_SIZE:
        return None, None

    bx = (x - START_X) // BOX_SIZE
    by = (y - START_Y) // BOX_SIZE
    return bx, by

print_board()


def is_board_full():
    for row in board:
        for col in row:
            if col == 0:
                return False
    return True


def has_winner(board):
    # check row
    if board[0][0] == board[0][1] == board[0][2] and board[0][0] != 0:
        return board[0][0]
    if board[1][0] == board[1][1] == board[1][2] and board[1][0] != 0:
        return board[1][0]
    if board[2][0] == board[2][1] == board[2][2] and board[2][0] != 0:
        return board[2][0]
    # check column
    if board[0][0] == board[1][0] == board[2][0] and board[0][0] != 0:
        return board[0][0]
    if board[0][1] == board[1][1] == board[2][1] and board[0][1] != 0:
        return board[0][1]
    if board[0][2] == board[1][2] == board[2][2] and board[0][2] != 0:
        return board[0][2]
    # check X lines
    if board[0][0] == board[1][1] == board[2][2] and board[0][0] != 0:
        return board[0][0]
    if board[0][2] == board[1][1] == board[2][0] and board[0][2] != 0:
        return board[0][2]
    # else
    return None


def draw_lines():
    pygame.draw.line(screen, BLACK,
                     (START_X, START_Y + BOX_SIZE),
                     (START_X + 3 * BOX_SIZE, START_Y + BOX_SIZE))
    pygame.draw.line(screen, BLACK,
                     (START_X, START_Y + 2 * BOX_SIZE),
                     (START_X + 3 * BOX_SIZE, START_Y + 2 * BOX_SIZE))
    pygame.draw.line(screen, BLACK,
                     (START_X + BOX_SIZE, START_Y ),
                     (START_X + BOX_SIZE, START_Y + 3 * BOX_SIZE))
    pygame.draw.line(screen, BLACK,
                     (START_X + 2 * BOX_SIZE, START_Y ),
                     (START_X + 2 * BOX_SIZE, START_Y + 3 * BOX_SIZE))


def draw_winner():
    if winner == man:
        screen.blit(o_win, (120, 120))
    if winner == ai:
        screen.blit(x_win, (120, 120))
    if winner == "tie":
        screen.blit(tie, (120, 120))


def draw_board():
    """根据数据绘制棋盘"""
    for ri,row in enumerate(board):
        for ci, col in enumerate(row):
            if col == 0:
                continue
            img = img_o if col == man  else img_x
            screen.blit(img, (START_X + ci * BOX_SIZE, START_Y + ri * BOX_SIZE))



clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONUP:
            bx, by = pos_to_board(pygame.mouse.get_pos())
            if bx != None and by != None:
                if board[by][bx] == 0:
                    board[by][bx] = current_turn

                    current_turn = ai if current_turn == man else man

                    w = has_winner(board)
                    if w != None:
                        winner = w
                    elif is_board_full():
                        winner = tie

                    # computer's turn
                    pos = AI.next(board)
                    print(pos)
                    if pos != None:
                        row, col = pos
                        if row != None and col != None:
                            board[row][col] = ai

                            current_turn = ai if current_turn == man else man

                    w = has_winner(board)
                    if w != None:
                        winner = w
                    elif is_board_full():
                        winner = "tie"

    # --------------- event ------------------

    # --------------- update ------------------

    # --------------- draw ------------------
    screen.fill(WHITE)

    draw_board()
    draw_lines()
    draw_winner()

    pygame.display.flip()
    # --------------- clock ------------------
    clock.tick(60)

